package com.jnxx.okr.controller;

import com.jnxx.basic.util.AjaxResult;
import com.jnxx.basic.util.GetStaffRequestUtil;
import com.jnxx.okr.vo.DelFileVo;
import com.jnxx.task.domain.OkrStaff;
import com.jnxx.task.mapper.TaskMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api")
public class UploadFileController {

    @Autowired
    private TaskMapper taskMapper;

    @RequestMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        System.out.println(file);
        String staffName = request.getParameter("staffName");
        try {
            // 配置本地文件保存路径，确保使用反斜杠 \ 作为分隔符
            String uploadDir = "D:\\JAVA\\okr\\files"; // 注意路径的分隔符是 \

//            String id = request.getParameter("id");
//            System.out.println("id：" + id);

            // 从上传的文件中获取文件名
            String fileName = file.getOriginalFilename();
            String name = file.getName();
            System.out.println("文件名：" + name);
            System.out.println("原始文件名:"+fileName);

            // 创建目标文件夹，如果不存在
            File uploadFolder = new File(uploadDir);
            if (!uploadFolder.exists()) {
                uploadFolder.mkdirs();
            }
            if (fileName != null){
                //检查文件是否重名
                if (checkFileName(fileName, uploadDir)){
                    return AjaxResult.error("-1", "文件重名，建议重命名");
                }
            }

            // 说明不是新增，是修改
//            if (!"undefined".equals(id)){
//                // 跟新这个id的附件
//                String names = request.getParameter("additionalData");
//                taskMapper.updateAnnexById(Long.parseLong(id),names);
//            }

            // 构建完整的文件路径
            String filePath = uploadDir + "\\" + fileName;

            System.out.println("文件路径:"+filePath);
            // 将文件保存到本地文件夹
            file.transferTo(new File(filePath));

            log.info("{}上传文件：{}",staffName, fileName);
            return AjaxResult.success(filePath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("-1", "文件传输错误");
        }
    }

    @GetMapping("/downFile/{fileName}")
//    @PostMapping("/downFile")
    public ResponseEntity<byte[]> downloadFile(@PathVariable("fileName") String fileName , HttpServletRequest request) {
//    public ResponseEntity<byte[]> downloadFile(@RequestBody Map<String, DelFileVo> delItem) {

//        DelFileVo fileVo = delItem.get("itedelItemm");
//        String fileNames = fileVo.getFileNames();
//        String fileName = fileVo.getName();
//        String suffix = fileName.split("\\.")[1];
        int i = fileName.lastIndexOf(".");
        String suffix = fileName.substring(i + 1);

        // 假设文件存储在服务器的某个目录中
        System.out.println("收到的fileName:"+ fileName);
        String filePath = "D:/JAVA/okr/files/"; // 替换为实际文件存储路径
        Resource file = null;

        try {
            file = new FileSystemResource(filePath + fileName);
        } catch (Exception e) {
            log.error("文件解析错误：{}", fileName);
        }

        if (file != null && file.exists()) {

            try {
                // 从 Resource 中获取文件内容
                InputStream inputStream = file.getInputStream();
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                byte[] binaryData = outputStream.toByteArray();

                // 设置 HTTP 响应头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentDispositionFormData("attachment", file.getFilename());
//                if ("xls".equals(suffix)){
//                    headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
//                } else if ("docx".equals(suffix) || "doc".equals(suffix)){
//                    headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
//                } else if ("jpn".equals(suffix) || "png".equals(suffix) || "jpeg".equals(suffix) || "jpg".equals(suffix)){
//                    headers.setContentType(MediaType.parseMediaType("image/jpeg"));
//                }
                switch (suffix) {
                    case "xls":
                        headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
                        break;
                    case "docx":
                    case "doc":
                        headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
                        break;
                    case "jpn":
                    case "png":
                    case "jpeg":
                    case "jpg":
                        headers.setContentType(MediaType.parseMediaType("image/jpeg"));
                        break;
                }
                // 返回二进制数据作为 ResponseEntity
                System.out.println("处理成功");
                return ResponseEntity
                        .ok()
                        .headers(headers)
                        .body(binaryData);

            } catch (Exception e) {
                // 处理下载文件失败的情况
                // 返回适当的错误响应
                log.error("文件下载错误：{}", fileName);
            }
        } else {
            // 文件不存在时的处理
            // 返回适当的错误响应
            log.error("文件不存在：{}", fileName);
        }
        return null;
    }

    @PostMapping("/delFile")
    public AjaxResult delFile(@RequestBody Map<String, DelFileVo> delItem){
        DelFileVo item = delItem.get("itedelItem");
        String fileName = item.getName();
        String fileNames = item.getFileNames();
        Long id = item.getId();
        OkrStaff staff = GetStaffRequestUtil.getStaff();
        System.out.println("删除的fileName:"+ fileName);
        String filePath = "D:/JAVA/okr/files/" + fileName; // 替换为实际文件存储路径

        // 创建 File 对象
        File file = new File(filePath);

        // 检查文件是否存在并删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("文件删除成功");
                log.info("{}删除文件：{}",staff.getName(), fileName);
                if (id != null){
                    taskMapper.updateAnnexById(id, fileNames);
                }
            } else {
                System.err.println("无法删除文件");
                return AjaxResult.error("-10", "无法删除文件");
            }
        } else {
            System.err.println("文件不存在或不是文件");
            return AjaxResult.error("-20", "文件不存在或不是文件");
        }
        return AjaxResult.success("删除成功");
    }


    public Boolean checkFileName(String fileName, String path){
        String filePath = path + "\\" + fileName;
        // 查看文件是否存在
        File file = new File(filePath);

        // 使用exists()方法来检查文件是否存在
        if (file.exists()) {
            log.error("文件存在:{}", fileName);
            return true;
        } else {
            log.info("文件不存在:{}", fileName);
            return false;
        }
    }
}
